package com.songcan.oauth.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.songcan.model.oauth.SysDept;
import com.songcan.oauth.service.SysDeptService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Objects;

@RequestMapping("rest/dept")
@RestController
@Slf4j
@AllArgsConstructor
@Validated
public class DeptController {

    private SysDeptService sysDeptService;


    @PostMapping()
    public void addDept(@NotBlank(message ="名称不能为空")String name,Long parentId,
                        String remark,Integer sort){
            sysDeptService.addDept(name,sort,parentId,remark);
    }

    @PutMapping()
    public void updateDept(@NotNull(message = "id不能为空")Long id, String name,
                           String remark, Integer status){
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(id);
        sysDept.setName(name);
        sysDept.setDelFlag(status);
        sysDept.setUpdateTime(new Date());
        sysDept.setRemark(remark);
        sysDeptService.saveOrUpdate(sysDept);
    }

    @GetMapping()
    public SysDept  getById(Long id){
        return  sysDeptService.getById(id);
    }

    @GetMapping("/list")
    public IPage<SysDept> list(String name,
                               @RequestParam(defaultValue = "1")Integer page,
                               @RequestParam(defaultValue = "20")Integer pageSize){


        LambdaQueryWrapper<SysDept> where = Wrappers.lambdaQuery(new SysDept());
        if(Objects.nonNull(name)&& StrUtil.isNotEmpty(name)){
            where.like(SysDept::getName,"%"+name+"%");
        }
        where.eq(SysDept::getDelFlag,0);
        where.orderByDesc(SysDept::getCreateTime);

        return sysDeptService.page(new Page<>(page,pageSize),where);
    }

}
